import { message } from 'antd';
import axios, { AxiosRequestConfig } from 'axios';
import _ from 'lodash';

import { BASE_URL } from './config';
import { getResourceId, getToken } from './index';

interface RequestOptions extends AxiosRequestConfig {
  params?: Record<string, any>;
  data?: Record<string, any>;
}

const responseCodes = ['200', 1000, '1000000000'];

// 创建 axios 实例
const axiosInstance = axios.create({
  baseURL: BASE_URL, // 从环境变量获取 API 基础 URL
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
  },
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    // 可以在这里添加token等认证信息
    const token = getToken();
    const resourceId = getResourceId();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    if (resourceId) {
      config.headers['Resourceid'] = resourceId;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    // 可以统一处理响应数据
    const resData = response.data;

    if (response.headers['content-disposition']) {
      const fileName = response.headers['content-disposition'].split('filename=')[1];
      const url = window.URL.createObjectURL(new Blob([resData]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', decodeURIComponent(fileName));
      document.body.appendChild(link);
      link.click();
      link.remove();
    } else {
      if (resData.code === 200) {
        message.success(resData.msg || resData.detail || resData.message || '操作成功', 5);
        return resData.data;
      }
      if (!_.isNumber(resData) && !_.isUndefined(resData.code) && !responseCodes.includes(resData.code)) {
        message.error(resData.msg || resData.detail || resData.message || 'Service Error', 5);
      }
    }
    console.log(resData, 'resData');
    return resData;
  },
  (error) => {
    // 统一处理错误
    const { response } = error;
    if (response?.status === 401) {
      // 处理未授权情况
      localStorage.removeItem('token');
      window.location.href = '/login';
    } else {
      message.error(response?.data?.error || 'Service Error', 5);
    }
    return Promise.reject(error);
  },
);

// 导出请求函数
export const request = async (url: string, options: RequestOptions = {}) => {
  try {
    const response = await axiosInstance({
      url,
      ...options,
    });

    if (_.isNumber(response) || _.isUndefined(response.code)) {
      return response;
    }

    console.log(response, 'response');
    return response.data === null ? responseCodes.includes(response.code) : response.data;
  } catch (error) {
    throw error;
  }
};
